package com.tbit.main.controller;

import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.Image;
import com.tbit.main.service.ImageService;
import com.tbit.main.util.LogUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.OutputStream;

/**
 * @Description: 广告控制
 */
@Validated
@RestController
@Slf4j
@RequestMapping(value = "/advert")
public class AdaccountController {

    @Autowired
    private ImageService imageService;

    /**
     * 获取图片信息
     *
     * @param imageId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("getImage")
    public void getImage(@NotNull(message = "ver.imageId.notNull") String imageId, HttpServletRequest request, HttpServletResponse response) {
        Image image = imageService.getByImageId(imageId);
        if (image == null) {
            throw new BaseException("image_not_exit");
        }
        try {
            if (image.getImageContent().length > 0) {
                OutputStream out = response.getOutputStream();
                try {
                    out.write(image.getImageContent());
                    out.flush();
                } catch (Exception e) {
                    e.getMessage();
                } finally {
                    out.close();
                }
            }
        } catch (Exception e) {
            LogUtil.warn("图片读取失败： " + e.getMessage());
            throw new BaseException("read_image_file");
        }

    }

}
